import React, {useState, forwardRef, useImperativeHandle, useEffect} from 'react';
import {
    EditableProTable, ProTable,
} from '@ant-design/pro-components';
import {Button, Modal, Space, Tooltip, Upload} from "antd";

import TheImage from "@/components/TheImage/index.jsx";
import {apiGoodsStockInfo} from "@/api/marketingTool";
import TheButton from "@/components/TheButton/index.jsx";

const Goods = forwardRef((props,ref) => {
    const selectKeys = props.value.map((item) => item.goodsId);
    const [editableKeys, setEditableRowKeys] = useState(() =>
        props.value.map((item) => item.goodsId),
    );
    const [dataSource, setDataSource] = useState(props.value || []);
    const [selectedRows, setSelectedRows] = useState([]);
    const [disabledKeys, setDisabledKeys] = useState([]);
    const [modalOpen, setModalOpen] = useState(false);
    const mode = props.mode;
    useEffect(()=>{
        if (mode === 'edit'){
            // 处理编辑时回显数据赋值给弹窗默认数据
            setSelectedRows(props.value)
            setDisabledKeys(props.value.map((item) => item.goodsId))
        }
    },[])
    useImperativeHandle(ref, () => ({
        open,resetData
    }));
    const open = () => {
        setModalOpen(true)
    }
    const resetData = () => {
        setDataSource([])
        setSelectedRows([])
    }
    const columns = [
        {
            title: '商品ID',
            dataIndex: 'goodsId',
            key: 'goodsId',
            editable: false,
            width: 200,
        },
        {
            title: "商品名称",
            dataIndex: "goodsName",
            key: "goodsName",
            ellipsis: true,
            editable: false,
            width: 300,
        },
        {
            title: '商品图片',
            dataIndex: 'goodsShowImages',
            key: 'goodsShowImages',
            editable: false,
            hideInSearch: true,
            width: 500,
            render: (text) => {
                return <TheImage src={text.split(',')} width={80} height={80}></TheImage>
            }
        },
        {
            title: '所属类目',
            dataIndex: 'goodsClassifyName',
            key: 'goodsClassifyName',
            editable: false,
            hideInSearch: true,
            width: 100
        },
        // {
        //     title: '商品原价',
        //     dataIndex: 'originalPrice',
        //     key: 'originalPrice',
        //     valueType: 'money',
        //     hideInSearch: true,
        //     editable: false
        // },
        // {
        //     title: '商品现价',
        //     dataIndex: 'currentPrice',
        //     key: 'currentPrice',
        //     valueType: 'money',
        //     hideInSearch: true,
        //     editable: false
        // },
        {
            title: '商品状态',
            dataIndex: 'goodsStatus',
            key: 'goodsStatus',
            editable: false,
            hideInSearch: true,
            valueEnum: {
                'Y': { text: '上架' },
                'N': { text: '下架' },
            },
            width: 150
        },
        {
            title: '上次操作时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            editable: false,
            hideInSearch: true,
            valueType: 'dateTime',
            width: 150
        },
    ]

    let tableProps = {}
    if (props.mode === 'view'){
        tableProps = {
            toolBarRender: false
        }
    }
    else {
        tableProps = {
            toolBarRender: (action) => {
                return action.toolBarRender
            }
        }
    }
    return <>
        {
            props.type === 'single' ? <Space>
                <Button
                    style={{marginBottom:20}}
                    key="new"
                    onClick={() => {
                        setModalOpen(true)
                    }}
                    disabled={mode === 'edit'}
                >
                    选择商品
                </Button>
            </Space>: null
        }
        <EditableProTable
            rowKey="goodsId"
            bordered={true}
            scroll={{x: 960 ,y: '500px'}}
            toolBarRender={false}
            columns={[...columns,{
                title: '操作',
                valueType: 'option',
                width: 250,
                fixed: "right",
                hideInTable: props.mode === 'view',
                render: () => {
                    return null;
                },
            }]}
            recordCreatorProps={false}
            value={dataSource}
            controlled={true}
            onChange={props.onValuesChange}
            editable={{
                type: 'multiple',
                editableKeys,
                onChange: setEditableRowKeys,
                actionRender: (row, _, dom) => {
                    return <Space style={{margin:"0 auto"}}>{disabledKeys.includes(row.goodsId) ?'无法删除':[dom.delete]}</Space>
                },
                onValuesChange: (record, recordList) => {
                    setSelectedRows(recordList);
                    setDataSource(recordList);
                },
            }}
            pagination={{
                defaultPageSize: 5
            }}
        />
        <Modal
            title={'选择用户'}
            width={'80%'}
            open={modalOpen}
            destroyOnClose={true}
            onOk={() => {
                setDataSource(selectedRows)
                setEditableRowKeys(selectedRows.map((item) => item.goodsId))
                props.onValuesChange(selectedRows)
                setModalOpen(false)
            }}
            onCancel={() => setModalOpen(false)}
        >
            <ProTable
                bordered={true}
                options={false}
                scroll={{ x: 960 ,y: '57vh'}}
                rowKey={(record) => record.goodsId}
                columns={columns}
                params={{
                    storeStatus: 'Y',
                    goodsStatus: 'Y',
                    reviewStatus: 'T',
                }}
                request={async (params, sort, filter) => {
                    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                    // 如果需要转化参数可以在这里进行修改
                    const res = await apiGoodsStockInfo({
                        pageNo: params.current,
                        pageSize: params.pageSize,
                        ...params
                    });
                    return {
                        data: res.data,
                        // success 请返回 true，
                        // 不然 table 会停止解析数据，即使有数据
                        success: res.code === 0,
                        // 不传会使用 data 的长度，如果是分页一定要传
                        total: res.totalCount,
                    };
                }}
                pagination={{
                    defaultPageSize: 10
                }}
                rowSelection={{
                    defaultSelectedRowKeys: selectKeys,
                    preserveSelectedRowKeys: true,
                    type: props.type === 'single'?'radio':'checkbox',
                    onChange: (keys, rows) => {
                        setSelectedRows((prev) => {
                            let arr = []
                            rows.forEach((item,index)=>{
                                if (item === undefined){
                                    arr.push(prev.find(v=>v.goodsId === keys[index]))
                                }
                                else{
                                    arr.push(item)
                                }
                            })
                            return arr;
                        });
                    },
                    getCheckboxProps: (record) => {
                        return {
                            disabled: disabledKeys.includes(record.goodsId),
                        }
                    },
                }}
                search={{
                    optionRender: (searchConfig,formProps,dom)=>{
                        return dom.reverse()
                    }
                }}
            />
        </Modal>
    </>
});

export default Goods;
